<script setup>
/* 引入 */
import { ref, onMounted, inject, watch } from "vue";
import { useRouter } from "vue-router";

/* 数据 */
const router = useRouter();

// 使用全局注入的 axios
const axios = inject("$axios");

// 文章列表数据
const articles = ref([]);

// 模拟获取 town 和 sort 参数
const props = defineProps({
  town: {
    type: String,
    required: true,
  },
  sort: {
    type: String,
    required: true,
  },
  maxItems: {
    type: Number,
    default: -1, // 默认全部显示
  },
});

// 获取文章列表的函数
const fetchArticles = async () => {
  try {
    const response = await axios.get("/articles/filter", {
      params: { town: props.town, sort: props.sort },
    });

    const textSize = 30;

    // 对每篇文章的内容进行截断处理，超过 15 个字符则加上省略号
    articles.value = response.data.map((article) => ({
      ...article,
      content:
        article.content.length > textSize
          ? article.content.slice(0, textSize) + "..."
          : article.content,
    }));

    // 如果文章数量超过 maxItems, 则增加一个带有省略号的项
    if (props.maxItems !== -1 && articles.value.length > props.maxItems) {
      articles.value = articles.value.slice(0, props.maxItems);
      articles.value.push({
        title: "...",
        content: "...",
        origin: "",
        _id: "more", // 这里的 _id 需要保证唯一
      });
    }
  } catch (error) {
    console.error("获取文章失败：", error);
  }
};

/* 钩子 */
// 在组件挂载时获取文章数据
onMounted(() => {
  fetchArticles();
});

/* 侦听 */
watch(
  // 指定侦听的目标
  () => props.town,
  // 发生改变时回调
  (newTown) => {
    if (newTown) {
      fetchArticles();
    }
  },
  { immediate: true }, // 这里的 immediate: true 确保在初次加载时也能触发
);

/* 回调 */
const goTo = (articlesId) => {
  router.push({
    path: `/articles/${articlesId}`,
  });
};
</script>

<template>
  <div class="article-list-container">
    <el-table :data="articles" stripe style="width: 99.5%">
      <el-table-column prop="title" label="标题" width="200" />
      <el-table-column prop="origin" label="作者" width="100" />
      <el-table-column prop="content" label="内容" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            v-if="scope.row._id !== 'more'"
            type="primary"
            plain
            @click="goTo(scope.row._id)"
          >
            查看
          </el-button>
          <span v-else>...</span>
          <!-- 显示省略号 -->
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.article-list-container {
  padding: 20px;
}
</style>
